<template>
  <div class="wx-auth-redirect">
    <tn-wx-login
      v-if="showWXLogin"
      class="wx-login"
      :appid="appid"
      scope="snsapi_login,snsapi_userinfo"
      :redirect-uri="redirectURI"
      theme="black"
      :self-redirect="true"
    />
  </div>
</template>

<script>
const defaultSettings = require('../../settings.js')
import TnWxLogin from '@/components/TNWXLogin'

export default {
  name: 'WxAuthLoginRedirect',
  components: { TnWxLogin },
  data() {
    return {
      urlParams: {},
      redirect: '',
      otherQuery: {},
      showWXLogin: false,
      appid: defaultSettings.wxAuthLoginAPPID,
      redirectURI: encodeURI(process.env.VUE_APP_BASE_URL + 'admin.php/admin/we_chat_login')
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // console.log('wx auth login')
    this.handleWXLoginRedirect()
  },
  methods: {
    handleWXLoginRedirect() {
      // console.log(this.otherQuery.code)
      if (!this.otherQuery.code) {
        this.showWXLogin = true
      } else {
        // console.log('redirect end')
        window.localStorage.setItem('tn-wx-admin-oauth-code', this.otherQuery.code)
      }
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
</style>
